package com.flexcloudsdk.fetch;
import java.util.logging.Logger;
import java.net.URL;
import java.io.IOException;
import java.util.concurrent.Future;

import com.flexcloudsdk.fetch.CloudHttpRequest;
import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;
import com.google.appengine.api.urlfetch.HTTPResponse;

public class CloudURLFetchService {
	private static final Logger log = Logger.getLogger(CloudURLFetchService.class.getName());
	private String sourceClass;
	private String sourceMethod;

	private URLFetchService fetchService;
	
	public CloudURLFetchService() {
		log.info("CloudURLFetchService has been created by BlazeDS");
		sourceMethod = Thread.currentThread().getStackTrace()[1].getMethodName().toString();
		sourceClass = CloudURLFetchService.class.getName();
		fetchService = URLFetchServiceFactory.getURLFetchService();
	}

	public void fetch(CloudHttpRequest request) {
		sourceMethod = Thread.currentThread().getStackTrace()[1].getMethodName().toString();
		log.info("Executing: " + sourceClass + "." + sourceMethod);

		try {
			fetchService.fetch(request.getRequest());
		} catch(IOException exception) {
			log.severe("IOException caught in fetch(request) for CloudURLFetchService");
		}
	}
	
	public void fetch(URL url) {
		sourceMethod = Thread.currentThread().getStackTrace()[1].getMethodName().toString();
		log.info("Executing: " + sourceClass + "." + sourceMethod);

		try {
		fetchService.fetch(url);
		} catch(IOException exception) {
			log.severe("IOException caught in fetch(url) for CloudURLFetchService");
		}
	}
	
	public  Future<HTTPResponse> fetchAsync(CloudHttpRequest request) {
		sourceMethod = Thread.currentThread().getStackTrace()[1].getMethodName().toString();
		log.info("Executing: " + sourceClass + "." + sourceMethod);

		return fetchService.fetchAsync(request.getRequest());
	}
	
	public Future<HTTPResponse> fetchAsync(URL url) {
		sourceMethod = Thread.currentThread().getStackTrace()[1].getMethodName().toString();
		log.info("Executing: " + sourceClass + "." + sourceMethod);
		return fetchService.fetchAsync(url);
	}
	
}
